package yang.itcode.controller;

import cn.hutool.json.JSONObject;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import yang.itcode.model.Result;
import yang.itcode.service.OtherCostService;

import static yang.itcode.constant.ErrorConstant.*;

@RestController
@RequestMapping("/api/other-cost")
public class OtherCostController {

    @Autowired
    private OtherCostService otherCostService;

    @PostMapping
    public Result<Object> addOtherCost(@RequestBody JSONObject obj) {
        if (otherCostService.addOtherCost(obj)) {
            return Result.success();
        } else {
            return Result.error(OTHER_COST_ADD_EXCEPTION_CODE, OTHER_COST_ADD_EXCEPTION_MESSAGE);
        }
    }

    @PostMapping("/list")
    public Result<PageInfo<JSONObject>> listOtherCosts(@RequestBody JSONObject obj) {
        Integer pageNum = obj.getInt("pageNum");
        Integer pageSize = obj.getInt("pageSize");
        JSONObject condition = obj.getJSONObject("condition");
        return Result.success(otherCostService.getOtherCostList(pageNum, pageSize, condition));
    }

    @GetMapping("/{id}")
    public Result<JSONObject> getDetail(@PathVariable("id") Integer id) {
        return Result.success(otherCostService.getOtherCostDetail(id));
    }

    @PutMapping
    public Result<Object> updateOtherCost(@RequestBody JSONObject obj) {
        if (otherCostService.updateOtherCost(obj)) {
            return Result.success();
        } else {
            return Result.error(OTHER_COST_UPDATE_EXCEPTION_CODE, OTHER_COST_UPDATE_EXCEPTION_MESSAGE);
        }
    }

    @DeleteMapping("/{id}")
    public Result<Object> deleteOtherCost(@PathVariable("id") Integer id) {
        if (otherCostService.deleteOtherCost(id)) {
            return Result.success();
        } else {
            return Result.error(OTHER_COST_DELETE_EXCEPTION_CODE, OTHER_COST_DELETE_EXCEPTION_MESSAGE);
        }
    }
}

